// @flow
import React from 'react'
import { DatePicker, Form, Input, Select, Button, message, Upload, Icon } from 'antd'
import { getSpecs } from 'utils/GeneralOptions'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './Home.css'
import R from 'ramda'
import DeviceContactList from 'components/DeviceContactList'
// import Tags from 'components/Tags'
const Dragger = Upload.Dragger
import { connect } from 'react-redux'
type Props = {
  userId: string,
  form: Object,
  history: Object
}

const FormItem = Form.Item
const Option = Select.Option

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type States = {
  data: Array<any>,
  pagination: Object,
  loading: boolean,
  types: Array<any>,
  specs: Array<any>,
  customers: Array<Object>,
  deviceTypes: Array<Object>,
  deviceStatus: Array<Object>,
  dataSource: Array<Object>,
  owner: Array<Object>,
  filterSpec: string,
  tagData: Array<string>,
  imageUrl: string,
  remoteImageUrl: string,
  contactData: Array<Object>,
  fileList: Array<Object>,
  customerId: string
}
class DeviceAdd extends React.Component {
  props: Props
  state: States
  goBack: Function
  checkNum: Function
  changeTags: Function
  changeFile: Function
  beforeUpload: Function
  getContact: Function
  changeFile1: Function
  changeCustomer: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      data: [],
      pagination: {},
      loading: false,
      types: [],
      specs: [],
      customers: [],
      deviceTypes: [],
      deviceStatus: [],
      dataSource: [],
      owner: [],
      filterSpec: '',
      tagData: [],
      imageUrl: '',
      remoteImageUrl: '',
      contactData: [],
      fileList: [],
      customerId: ''
    }

    this.goBack = this.goBack.bind(this)
    this.checkNum = this.checkNum.bind(this)
    this.changeTags = this.changeTags.bind(this)
    this.changeFile = this.changeFile.bind(this)
    this.changeFile1 = this.changeFile1.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
    this.getContact = this.getContact.bind(this)
    this.changeCustomer = this.changeCustomer.bind(this)
  }

  componentDidMount () {
    this.getCustomers()
    this.getStatus()
    this.getUsers()
    this.getDeviceTypes()
  }

  changeCustomer (value) {
    this.setState({
      customerId: value
    })
  }

  checkNum (rule, value, callback) {
    const checkReg = /^[0-9][Z0-9_]*$/
    if (value && !checkReg.test(value)) {
      callback('只能以数字开头, 且只能包含数字和下划线')
    } else {
      callback()
    }
  }

  /**
   * [handleTypeChange description]
   * @param  {[type]} value [description]
   * @return {[type]}       [description]
   */
  handleTypeChange = (value) => {
    this.setState({
      filterSpec: ''
    })
    const { deviceTypes } = this.state
    const filterType = deviceTypes.filter((item) => {
      return `${item.id}` === value
    })
    this.props.form.setFieldsValue({ spec: filterType[0].spec })
    getSpecs(filterType[0].type, (json) => {
      this.setState({
        specs: json.result.map((d, i) => {
          return <Option key={d.id} value={d.value}>{d.label}</Option>
        }),
        filterSpec: filterType[0].spec
      })
    })
  }
  goBack () {
    const { history } = this.props
    history.push('/business/device-info')
  }

  changeTags (tagData) {
    this.setState({
      tagData
    })
  }
  getContact (data: Array<Object>) {
    this.setState({
      contactData: data
    })
  }
  /**
   * 提交表单
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      const { imageUrl, contactData } = this.state
      const values = {
        ...Object.assign({}, fieldsValue, { imageUrl }),
        'contacts': contactData,
        'keyName': this.state.tagData.join(','),
        'produceDate': fieldsValue.produceDate
          ? fieldsValue['produceDate'].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ') : '',
        'operationDate': fieldsValue.operationDate
          ? fieldsValue['operationDate'].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ') : ''
      }
      values.fileList = values.fileUrl ? values.fileUrl.fileList : []
      console.log(values)
      universalFetch(`${__SERVICE_API__}device/devices`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(values)
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('设备添加成功')
        this.props.history.push('/business/device-info')
        this.setState({
          loading: false
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        this.setState({
          loading: false
        })
        message.error('设备添加失败： ' + err.message, 10)
      })
    })
  }

  getCustomers () {
    universalFetch(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageSize=20000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          customers: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getDeviceTypes () {
    universalFetch(`${__SERVICE_API__}device/templates/devices?type=deep`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const deviceTypes = []
        json.result.map((item) => {
          if (item.children && item.children.length > 0) {
            // this.mapDevicesData(item, deviceTypes)
            deviceTypes.push(R.omit(['children'], item))
          } else {
            deviceTypes.push(item)
          }
        })
        this.setState({
          types: deviceTypes.map((d, i) => {
            return <Option key={d.id} value={`${d.id}`}>{d.name}</Option>
          }),
          deviceTypes
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getUsers () {
    universalFetch(`${__SERVICE_API__}sys/users?pageSize=20000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          owner: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  changeFile (info) {
    const response = info.file.response
    if (response && response.code === 200000) {
      this.setState({
        imageUrl: response.result.name,
        remoteImageUrl: response.result.url
      })
    }
  }
  changeFile1 (info) {
    console.log(info)
    let fileList = info.fileList
    // 1. Limit the number of uploaded files
    //    Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-10)
    // 2. read from response and show file link
    fileList = fileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.result.url
        file.name = file.name
      }
      return file
    })
    // 3. filter successfully uploaded files according to response from server
    fileList = fileList.filter((file) => {
      const status = info.file.status
      if (status === 'done') {
        return file.response.status === 'success'
      }
      return true
    })
    console.log(fileList)
    this.setState({ fileList: fileList })
  }

  beforeUpload (file) {
    const type = file.type.toLocaleLowerCase()
    if (type.indexOf('image/') === -1) {
      message.error('只能上传图片', 3)
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于2MB!')
    }
    return type.indexOf('image/') > -1
  }
  getStatus () {
    const types = ['deviceStatus', 'dataSource']
    // $FlowFixMe
    universalFetch(`${__SERVICE_API__}device/conditions?types=${types}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          deviceStatus: json.result.deviceStatus,
          dataSource: json.result.dataSource
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { customers, filterSpec, loading, deviceStatus, dataSource, owner, remoteImageUrl } = this.state
    const specFieldDecorator = filterSpec
      ? getFieldDecorator('spec', {
        initialValue: filterSpec
      })
      : getFieldDecorator('spec', {
      })
    const token = localStorage.getItem('asset_token')

    const props1 = {
      name: 'file',
      multiple: true,
      showUploadList: true,
      headers:{ 'X-Auth':token },
      action: `${__SERVICE_API__}static/statics`,
      onChange: this.changeFile1
    }
    return (
      <div className={styles['main']}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label='设备编号' hasFeedback>
            {getFieldDecorator('deviceNo', {
              rules: [
                { required: true, message: '请填写设备编号', whitespace: true },
                { validator: this.checkNum }
              ]
            })(
              <Input placeholder='请填写设备编号' ref={(e) => {
                document.querySelector('#deviceNo').focus()
              }} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='设备模板'>
            {getFieldDecorator('tdeviceId', {
              // rules: [
                // { required: true, message: '请选择设备模板' }
              // ]
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} style={{ width: 280 }}
                placeholder='请选择设备模板'
                onChange={this.handleTypeChange}>
                {this.state.types}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='型号'>
            {specFieldDecorator(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} style={{ width: 280 }}
                placeholder='请选择型号'
                >
                {this.state.specs}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='名字' hasFeedback>
            {getFieldDecorator('name', {
              rules: [
                { required: true, message: '请填写名字', whitespace: true }
              ]
            })(
              <Input placeholder='请填写名字' />
            )}
          </FormItem>
          {/* <FormItem {...formItemLayout} label='全称' hasFeedback>
            {getFieldDecorator('fullName', {})(
              <Input placeholder='请填写全称' />
            )}
          </FormItem> */}
          <FormItem {...formItemLayout} label='产品编号' hasFeedback>
            {getFieldDecorator('pinCode', {})(
              <Input placeholder='请填写pinCode' />
            )}
          </FormItem>

          <FormItem {...formItemLayout} label='制造商' hasFeedback>
            {getFieldDecorator('certificateNo', {})(
              <Input placeholder='请填写制造商名称' />
            )}
          </FormItem>
          {/* <FormItem {...formItemLayout} label='键相' hasFeedback>
            {getFieldDecorator('keyName', {
            })(
              <div>
                <Input style={{ display:'none' }} placeholder='请填写键相(1,2,3)' />
                <Tags deValue={[]} onChange={this.changeTags} />
              </div>
            )}
          </FormItem> */}
          <FormItem {...formItemLayout} label='生产日期'>
            {getFieldDecorator('produceDate')(
              <DatePicker placeholder='请选择生产日期' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='投用日期'>
            {getFieldDecorator('operationDate')(
              <DatePicker placeholder='请选择投用日期' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='设备状态'>
            {
              getFieldDecorator('status', {
                initialValue: deviceStatus.length > 0 ? deviceStatus[0].value : ''
              })(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} style={{ width:280 }} placeholder='请选择设备状态'>
                  {
                    deviceStatus.map((item, i) => {
                      return <Option key={i} value={item.value}>
                        {item.label}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='设备负责人'>
            {getFieldDecorator('owner', {})(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} style={{ width: 280 }}>
                {
                  owner.map((item, i) => {
                    return <Option key={i} value={item.id}>
                      {item.loginName}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='数据源'>
            {getFieldDecorator('dataSource', {})(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} style={{ width: 280 }}>
                {
                  dataSource.map((item, i) => {
                    return <Option key={i} value={item.value}>
                      {item.label}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='所属客户'>
            {getFieldDecorator('customerId', {
              rules: [
                { required: true, message: '请选择所属客户' }
              ]
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择客户'
                onChange={this.changeCustomer}
                >
                {
                  customers.map((customer, i) => {
                    return <Option key={i} value={`${customer.id}`}>
                      {customer.name}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='联系人'>
            {getFieldDecorator('contacts')(
              <DeviceContactList customerId={this.state.customerId} contactData={[]} getContact={this.getContact} />
            )}
          </FormItem>
          {
          //   <FormItem {...formItemLayout} label=''>
          //   {getFieldDecorator('contact', {
          //     rules: [
          //       // { required: true, message: '请填写联系人' }
          //     ]
          //   })(
          //     <input />
          //   )}
          // </FormItem>
        }
          <FormItem {...formItemLayout} label='备注' hasFeedback>
            {getFieldDecorator('remark', {})(
              <Input placeholder='请填写备注' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='设备图片'>
            {
              getFieldDecorator('imageUrl', {})(
                <Upload
                  {...{
                    name: 'file',
                    className: styles['avatar-uploader'],
                    action: `${__SERVICE_API__}static/statics`,
                    headers:{ 'X-Auth':token },
                    onChange: this.changeFile,
                    beforeUpload: this.beforeUpload,
                    showUploadList: false
                  }}
                  >
                  {
                    remoteImageUrl
                    ? <div className={styles['image-preview']}>
                      <img src={remoteImageUrl} style={{ width: '100%' }} />
                      <div className={styles['over-avatar']}>
                        更换图片
                      </div>
                    </div>
                    : <Button style={{ width: '150px' }}>
                      <Icon type='upload' />上传图片
                    </Button>
                  }
                </Upload>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='文件'>
            {
              getFieldDecorator('fileUrl', {})(
                <Dragger {...props1}>
                  <p className='ant-upload-drag-icon'>
                    <Icon type='inbox' />
                  </p>
                  <p className='ant-upload-text'>点击或者拖拽文件到该区域</p>
                  <p className='ant-upload-hint'>支持单个或批量上传</p>
                </Dragger>
              )
            }
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary' htmlType='submit' size='large'
              loading={loading}
              >保存</Button>
            <Button style={{ marginLeft: '20px' }}
              onClick={this.goBack}
              >返回</Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Form.create()(DeviceAdd))
